package com.xish.util;

import com.google.gson.JsonObject;
import com.xish.exception.XishException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;

/**
 * Created by zhanghuyi on 15/7/28.
 */
public class HttpClientUtil {
    private static final String CONTENT_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";
    private static final String CHARSET = "UTF-8";

    private static int CONNECTION_TIMEOUT = 20000;//请求超时
    private static int  SO_TIMEOUT = 20000;//读超时

    /**
     * post 方式请求
     * 将参数转成JSON格式，然后以 StringRequestEntity 进行请求
     * */
    public static String post(String url,Map<String,String> params) throws XishException {
        Set<Map.Entry<String, String>> entries = params.entrySet();
        JsonObject jsonObject = new JsonObject();
        for(Map.Entry<String, String> e:entries){
            jsonObject.addProperty(e.getKey(), e.getValue());
        }
        HttpClient httpClient=new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(SO_TIMEOUT);
        //使用POST方法
        PostMethod method = null;
        try {
            method = new PostMethod(url);
            method.setRequestEntity(new StringRequestEntity(jsonObject.toString(), CONTENT_TYPE, CHARSET));
            method.setRequestHeader("X-HTTP-Method-Override", "get");
            httpClient.executeMethod(method);
            String resp = method.getResponseBodyAsString();
            return resp;
        } catch (UnsupportedEncodingException e) {
            throw new XishException("不支持的编码方式："+e.getMessage(),e);
        } catch (IOException e){
            throw new XishException("网络异常："+e.getMessage(),e);
        } catch (Exception e){
            throw new XishException("未知异常："+e.getMessage(),e);
        }finally {
           if(method!=null){
               method.releaseConnection();//释放链接
           }
        }
    }
}
